package com.expert.miniapp.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.expert.miniapp.config.OSSConfig;
import com.expert.miniapp.service.OSSService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * OSSServiceImpl - 阿里云OSS服务实现类
 *
 * @author System
 * @since 2025-01-14
 */
@Service
public class OSSServiceImpl implements OSSService {

    private static final Logger logger = LoggerFactory.getLogger(OSSServiceImpl.class);

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadAvatar(MultipartFile file, String userId) throws Exception {
        // 验证文件
        validateFile(file);

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        String fileName = System.currentTimeMillis() + "_" + originalFilename;
        String objectName = ossConfig.getBasePath() + userId + "/" + fileName;

        logger.info("开始上传文件到OSS: userId={}, objectName={}", userId, objectName);

        OSS ossClient = null;
        try {
            // 创建OSS客户端
            ossClient = new OSSClientBuilder().build(
                    "https://" + ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret()
            );

            // 上传文件
            InputStream inputStream = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectName,
                    inputStream
            );

            ossClient.putObject(putObjectRequest);

            // 生成文件访问URL
            String fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;

            logger.info("文件上传成功: {}", fileUrl);
            return fileUrl;

        } catch (Exception e) {
            logger.error("文件上传失败", e);
            throw new Exception("文件上传失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void deleteFile(String fileUrl) throws Exception {
        OSS ossClient = null;
        try {
            // 从URL中提取objectName
            String objectName = extractObjectNameFromUrl(fileUrl);

            // 创建OSS客户端
            ossClient = new OSSClientBuilder().build(
                    "https://" + ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret()
            );

            // 删除文件
            ossClient.deleteObject(ossConfig.getBucketName(), objectName);

            logger.info("文件删除成功: {}", objectName);

        } catch (Exception e) {
            logger.error("文件删除失败", e);
            throw new Exception("文件删除失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new Exception("文件不能为空");
        }

        // 检查文件大小
        if (file.getSize() > ossConfig.getMaxFileSize()) {
            throw new Exception("文件大小不能超过" + (ossConfig.getMaxFileSize() / 1024 / 1024) + "MB");
        }

        // 检查文件扩展名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        List<String> allowedExtensions = Arrays.asList(ossConfig.getAllowedExtensions().split(","));

        if (!allowedExtensions.contains(fileExtension.toLowerCase())) {
            throw new Exception("不支持的文件格式，仅支持: " + ossConfig.getAllowedExtensions());
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    /**
     * 从URL中提取objectName
     */
    private String extractObjectNameFromUrl(String fileUrl) {
        // URL格式: https://bucket-name.endpoint/path/to/file
        String prefix = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/";
        if (fileUrl.startsWith(prefix)) {
            return fileUrl.substring(prefix.length());
        }
        throw new IllegalArgumentException("无效的文件URL");
    }
}
